using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UI;
using UnityEngine;
using UnityEngine.UI;

public class QiQiao : MonoBehaviour
{
    public EItemType m_getItemType;
    public string m_successTriggerScenario;
    
    private class Data
    {
        public RectTransform root;
        public QiQiaoInfo info;
        public Vector2 pos;
    }
    private Data[] m_qiQiaoArr;

    private void Awake()
    {
        var rectTransform = transform as RectTransform;
        var uiCamera = GameObject.Find("UICamera").GetComponent<Camera>();

        var contentRoot = transform.Find("Content");
        var startPosRoot = transform.Find("StartPos");
        m_qiQiaoArr = new Data[contentRoot.childCount];
        for (int i = 0; i < m_qiQiaoArr.Length; i++)
        {
            var child = contentRoot.GetChild(i) as RectTransform;
            m_qiQiaoArr[i] = new Data
            {
                root = child,
                info = child.GetComponent<QiQiaoInfo>(),
                pos = child.anchoredPosition,
            };
            if (i < 2) continue;
            child.GetComponent<Image>().alphaHitTestMinimumThreshold = 0.1f;
            //重置位置
            var startPos = startPosRoot.GetChild(i - 2) as RectTransform;
            child.anchoredPosition = startPos.anchoredPosition;
            child.localEulerAngles = startPos.localEulerAngles;
            //注册移动
            var listener = EventTriggerListener.Get(child.gameObject);
            var moveOffset = Vector2.zero;
            listener.onPointDown = _ =>
            {
                child.SetAsLastSibling();
            };
            listener.onBeginDrag = eventData =>
            {
                if (RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, uiCamera, out var localPoint))
                {
                    Vector2 pos = child.localPosition;
                    moveOffset = localPoint - pos;
                }
            };
            listener.onDrag = eventData =>
            {
                if (RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, uiCamera, out var localPoint))
                {
                    child.localPosition = localPoint - moveOffset;
                }
            };
            listener.onEndDrag = _ =>
            {
                CheckComplete();
            };
            var rotating = false;
            var clickCount = 0;
            var lastClickTime = Time.realtimeSinceStartup;
            listener.onClick = _ =>
            {
                if (rotating) return;
                var cur = Time.realtimeSinceStartup;
                var delta = cur - lastClickTime;
                if (delta > 0.3f) clickCount = 0;
                lastClickTime = cur;
                clickCount++;
                if (clickCount >= 2)
                {
                    rotating = true;
                    child.DOLocalRotate(child.localEulerAngles + new Vector3(0, 0, 45f), 0.3f).OnComplete(() =>
                    {
                        rotating = false;
                        CheckComplete();
                    });
                }
            };
        }
    }

    private void CheckComplete()
    {
        for (int i = 0; i < m_qiQiaoArr.Length; i++)
        {
            var data = m_qiQiaoArr[i];
            var rectTransform = data.root;
            var posDelta = rectTransform.anchoredPosition - data.pos;
            if (Mathf.Abs(posDelta.x) > 20 || Mathf.Abs(posDelta.y) > 20)
            {
                return;
            }
            var any = false;
            var euler = rectTransform.localEulerAngles.z;
            while (euler < 0) euler += 360f;
            euler %= 360; 
            for (int j = 0; j < data.info.validEulerList.Count; j++)
            {
                var other = data.info.validEulerList[j];
                if (Mathf.Abs(euler - other) < 10)
                {
                    any = true;
                    break;
                }
            }
            if (!any)
            {
                return;
            }
        }
        Debug.Log("通关!");
        for (int i = 0; i < m_qiQiaoArr.Length; i++)
        {
            var data = m_qiQiaoArr[i];
            var rectTransform = data.root;
            rectTransform.DOAnchorPos(data.pos, 1f).OnComplete(() =>
            {
                UI_LittleGamePanel.Pass();
                if (m_getItemType != EItemType.None) InventoryManager.AddItem(m_getItemType);
                if (!string.IsNullOrEmpty(m_successTriggerScenario)) UI_ScenarioPanel.StartScenario(m_successTriggerScenario);
            });
        }
    }
}
